package com.luck.easyfoodbatch.ui;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.LayoutRes;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;

import com.luck.easyfoodbatch.App;
import com.luck.easyfoodbatch.R;
import com.luck.easyfoodbatch.dialog.ShowProgressDialog;
import com.luck.easyfoodbatch.entity.User;
import com.luck.easyfoodbatch.swipbackhelper.SwipeBackHelper;
import com.luck.easyfoodbatch.util.HttpUtil;
import com.luck.easyfoodbatch.util.T;
import com.luck.easyfoodbatch.util.ToolbarUtil;

import java.lang.reflect.Field;
import java.lang.reflect.Method;

public class BaseNoSliderActivity extends AppCompatActivity {
    private final String TAG = "BaseActivity";
    protected Context mContext;
    // 页面无 Navigation 的模式
    public static final int MODE_NO_NAVIGATION = 0;
    // 页面有返回 Navigation 的模式
    public static final int MODE_BACK_NAVIGATION = 1;
    protected ImageButton left_back;
    protected TextView tv_title;
    protected TextView right_title;
    protected SharedPreferences sp;
    protected SharedPreferences.Editor edit;
    protected InputMethodManager manager;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        //StatusBarLightMode(this);
        super.onCreate(savedInstanceState);
        mContext = this;
        setContentViewXml();
    }

    /**
     * 设置状态栏黑色字体图标，
     * 适配4.4以上版本MIUIV、Flyme和6.0以上版本其他Android
     *
     * @param activity
     * @return 1:MIUUI 2:Flyme 3:android6.0
     */
    public static int StatusBarLightMode(Activity activity) {
        int result = 0;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            if (MiuiStatusBarDarkMode(activity, true)) {
                result = 1;
            } else if (FlymeSetStatusBarLightMode(activity, true)) {
                result = 2;
            } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                activity.getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
                result = 3;
            }
        }
        return result;
    }

    /**
     * 设置状态栏图标为深色和魅族特定的文字风格
     * 可以用来判断是否为Flyme用户
     *
     * @param dark 是否把状态栏字体及图标颜色设置为深色
     * @return boolean 成功执行返回true
     */
    public static boolean FlymeSetStatusBarLightMode(Activity activity, boolean dark) {
        boolean result = false;
        try {
            WindowManager.LayoutParams lp = activity.getWindow().getAttributes();
            Field darkFlag = WindowManager.LayoutParams.class
                    .getDeclaredField("MEIZU_FLAG_DARK_STATUS_BAR_ICON");
            Field meizuFlags = WindowManager.LayoutParams.class
                    .getDeclaredField("meizuFlags");
            darkFlag.setAccessible(true);
            meizuFlags.setAccessible(true);
            int bit = darkFlag.getInt(null);
            int value = meizuFlags.getInt(lp);
            if (dark) {
                value |= bit;
            } else {
                value &= ~bit;
            }
            meizuFlags.setInt(lp, value);
            activity.getWindow().setAttributes(lp);
            result = true;
        } catch (Exception e) {

        }
        return result;
    }

    /**
     * 设置状态栏字体颜色
     *
     * @param activity
     * @param darkmode
     * @return
     */
    public static boolean MiuiStatusBarDarkMode(Activity activity, boolean darkmode) {
        Class<? extends Window> clazz = activity.getWindow().getClass();
        try {
            int darkModeFlag = 0;
            Class<?> layoutParams = Class.forName("android.view.MiuiWindowManager$LayoutParams");
            Field field = layoutParams.getField("EXTRA_FLAG_STATUS_BAR_DARK_MODE");
            darkModeFlag = field.getInt(layoutParams);
            Method extraFlagField = clazz.getMethod("setExtraFlags", int.class, int.class);
            extraFlagField.invoke(activity.getWindow(), darkmode ? darkModeFlag : 0, darkModeFlag);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    // 布局数据初始化
    protected void setContentViewXml() {
        mContext = this;
        manager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        sp = getSharedPreferences("userInfo", MODE_PRIVATE);
        edit = sp.edit();
        SwipeBackHelper.onCreate(this);
        SwipeBackHelper.getCurrentPage(this).setDisallowInterceptTouchEvent(false)//不抢占事件，默认关（事件将先由子View处理再由滑动关闭处理）
                .setSwipeBackEnable(false)//设置是否可滑动
                .setSwipeSensitivity(0.5f)//对横向滑动手势的敏感程度。0为迟钝 1为敏感
                .setSwipeRelateEnable(true)//是否与下一级activity联动(微信效果)。默认关
                .setSwipeRelateOffset(300);
    }

    @Override
    public void setContentView(@LayoutRes int layoutResID) {
        super.setContentView(layoutResID);
    }

    // 重载 setContentView
    public void setContentView(@LayoutRes int layoutResID, int resTitleID, int pageMODE) {
        super.setContentView(layoutResID);
        // setToolbarStatus();
        left_back = $(R.id.left_back);
        tv_title = $(R.id.tv_title);
        right_title = $(R.id.right_title);
        tv_title.setText(resTitleID);
        switch (pageMODE) {
            case MODE_NO_NAVIGATION:
                // 页面没有返回箭头
                break;

            case MODE_BACK_NAVIGATION:
                // 页面有返回剪头
                left_back.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        backClick();
                    }
                });
                break;
            // 其它
        }
    }

    // 重载 setContentView
    public void setContentView(@LayoutRes int layoutResID, String title, int pageMODE) {
        super.setContentView(layoutResID);
        // setToolbarStatus();
        left_back = $(R.id.left_back);
        tv_title = $(R.id.tv_title);
        right_title = $(R.id.right_title);
        tv_title.setText(title);
        switch (pageMODE) {
            case MODE_NO_NAVIGATION:
                // 页面没有返回箭头
                break;

            case MODE_BACK_NAVIGATION:
                // 页面有返回剪头
                left_back.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        backClick();
                    }
                });
                break;
            // 其它
        }
    }

    /**
     * @return void 返回类型
     * @Title: backClick
     * @Description: 返回键
     * @author luck
     */
    public void backClick() {
        finish();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        SwipeBackHelper.onDestroy(this);
    }

    @Override
    protected void onPostCreate(Bundle savedInstanceState) {
        super.onPostCreate(savedInstanceState);
        SwipeBackHelper.onPostCreate(this);
    }

    // 重载 setContentView
    public void setContentView(@LayoutRes int layoutResID, int resTitleID, String rightTitle, int pageMODE) {
        super.setContentView(layoutResID);
        // setToolbarStatus();
        left_back = $(R.id.left_back);
        tv_title = $(R.id.tv_title);
        right_title = $(R.id.right_title);
        tv_title.setText(resTitleID);
        right_title.setText(rightTitle);
        switch (pageMODE) {
            case MODE_NO_NAVIGATION:
                // 页面没有返回箭头
                break;

            case MODE_BACK_NAVIGATION:
                // 页面有返回剪头
                left_back.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        backClick();
                    }
                });
                break;
            // 其它
        }
    }

    // 重载 setContentView
    public void setContentView(@LayoutRes int layoutResID, String title, String rightTitle, int pageMODE) {
        super.setContentView(layoutResID);
        // setToolbarStatus();
        left_back = $(R.id.left_back);
        tv_title = $(R.id.tv_title);
        right_title = $(R.id.right_title);
        tv_title.setText(title);
        right_title.setText(rightTitle);
        switch (pageMODE) {
            case MODE_NO_NAVIGATION:
                // 页面没有返回箭头
                break;

            case MODE_BACK_NAVIGATION:
                // 页面有返回剪头
                left_back.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        backClick();
                    }
                });
                break;
            // 其它
        }
    }


    // 设置状态栏颜色
    protected void setToolbarStatus() {
        ToolbarUtil.setColor(this, getResources().getColor(R.color.colorPrimaryDark));
    }

    @SuppressWarnings("unchecked")
    public <T> T $(int resID) {
        return (T) findViewById(resID);
    }

    protected void showToast(String msg) {
        Toast.makeText(BaseNoSliderActivity.this, msg, Toast.LENGTH_SHORT).show();
    }

    /**
     * @param clz
     * @return void 返回类型
     * @Title: startActivity
     * @Description: 进入到下个activity
     * @author luck
     */
    protected void startAct(Class clz) {
        Intent intent = new Intent(mContext, clz);
        startActivity(intent);
    }

    /**
     * @param clz
     * @return void 返回类型
     * @Title: startActivity
     * @Description: 进入到下个activity
     * @author luck
     */
    protected void startAct(Class clz, Bundle bundle) {
        Intent intent = new Intent(this, clz);
        intent.putExtras(bundle);
        startActivity(intent);
    }

    /**
     * @param clz
     * @return void 返回类型
     * @Title: startActivity
     * @Description: 进入到下个activity, 并关闭当前Activity
     * @author luck
     */
    protected void startFinishAct(Class clz, Bundle bundle) {
        Intent intent = new Intent(this, clz);
        intent.putExtras(bundle);
        startActivity(intent);
        finish();
    }


    /**
     * 隐藏软键盘
     */
    private void hideKeyboard(EditText editText) {
        InputMethodManager inputMethodManager =
                (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        inputMethodManager.hideSoftInputFromWindow(editText.getWindowToken(), 0);
    }

    /**
     * 显示软键盘
     */
    private void showKeyboard(EditText editText) {
        if (getWindow().getAttributes().softInputMode != WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN) {
            if (getCurrentFocus() != null)
                manager.showSoftInput(editText, InputMethodManager.SHOW_FORCED);
        }
    }

    /**
     * 判断是否登录
     *
     * @return
     */
    protected boolean isCheckedLogin() {
        User user = (User) App.getInstance().readObject(HttpUtil.USER_KEY);
        if (user == null || TextUtils.isEmpty(user.getUid() + "")) {
            return false;
        }
        return true;
    }


    /**
     * 广播发送者
     *
     * @param action
     */
    protected void sendBroadcast(String action) {
        Intent intent = new Intent();
        intent.setAction(action);
        sendBroadcast(intent);
    }

    /**
     * 注册发送者
     *
     * @param action
     */
    protected void registerReceiver(BroadcastReceiver receiver, String... action) {
        IntentFilter intentFilter = new IntentFilter();
        for (int i = 0; i < action.length; i++) {
            intentFilter.addAction(action[i]);
        }
        registerReceiver(receiver, intentFilter);
    }


    /**
     * 加载提示
     */
    private ShowProgressDialog dialog;

    protected void showProgressDialog(String msg) {
        dialog = new ShowProgressDialog(this);
        dialog.setContent(msg);
        dialog.show();
    }


    protected void hideShowProgress() {
        if (dialog != null && dialog.isShowing()) {
            dialog.dismiss();
        }
    }
}
